import { urlReg } from '@/utils/utils';
import {
  ModalForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  // ProFormUploadButton,
} from '@ant-design/pro-form';
import { Button, message, Upload } from 'antd';
import type { RcFile } from 'antd/lib/upload';
import { useState } from 'react';
import { updateWebNav } from '../service';
import type { UpdateWebNavType, WebNavTableListItem } from '../typings.d';
import ImgCrop from 'antd-img-crop';
import type { UploadFile } from 'antd/lib/upload/interface';
import Modal from 'antd/lib/modal/Modal';
import UploadOutlined from '@ant-design/icons/lib/icons/UploadOutlined';

const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

const UpdateWebNavModal = (props: {
  reload: () => void;
  webInfo: WebNavTableListItem;
  visible: boolean;
  setUnvisible: () => void;
}) => {
  const { reload, webInfo, visible, setUnvisible } = props;
  const [bannerUrl, setBannerUrl] = useState<string>(webInfo.bannerUrl);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');

  return (
    <ModalForm<UpdateWebNavType>
      title="更新网址导航"
      layout="horizontal"
      width={600}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => {
          setUnvisible();
        },
      }}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      visible={visible}
      initialValues={{
        platformName: webInfo.platformName,
        url: webInfo.url,
        status: webInfo.status,
        description: webInfo.description,
        priority: webInfo.priority,
      }}
      onFinish={async (values) => {
        const res = await updateWebNav(webInfo._id, {
          bannerUrl,
          platformName: values.platformName,
          url: values.url,
          status: values.status,
          description: values.description,
          priority: values.priority,
        });
        if (res.success) {
          message.success({ content: res.message, key: 'update_webnav' });
          reload();
          setUnvisible();
          return true;
        }
        message.error({ content: res.message, key: 'update_webnav' });
        return false;
      }}
    >
      <ProFormText
        label="平台名称"
        required
        name="platformName"
        rules={[
          {
            validator: (_, val) => {
              if (!val || val.length < 2)
                return Promise.reject(new Error('用户名称长度不得低于2位'));
              return Promise.resolve(val);
            },
          },
        ]}
      />
      <ProFormText
        label="平台地址"
        required
        name="url"
        rules={[
          {
            validator: (_, val) => {
              if (!val || !urlReg.test(val)) return Promise.reject(new Error('错误的url格式'));
              return Promise.resolve(val);
            },
          },
        ]}
      />
      <ProFormSelect
        label="平台类型"
        name="status"
        options={[
          { value: 0, label: '公有' },
          { value: 1, label: '私有' },
        ]}
      />
      <ProFormDigit
        label="平台优先级"
        name="priority"
        placeholder="请输入平台优先级, 数值越大优先级越低"
        min={1}
        max={99}
        fieldProps={{
          precision: 0,
          step: 1,
        }}
      />
      <ProFormTextArea label="平台备注" name="description" />
      <div style={{ padding: '0 70px', display: 'flex' }}>
        <div style={{ width: '85px' }}>上传图片：</div>
        <ImgCrop
          grid
          aspect={346 / 235.2}
          quality={1}
          beforeCrop={(file: File): Promise<boolean> =>
            new Promise<boolean>((resolve, rejects) => {
              const { name } = file;
              // .xlsx*表示匹配所有带有 .xlsx 的字段，$表示匹配字符串结尾位置
              const nameRegExp = new RegExp('(.jpeg|.png|.jpg)$');
              const isImage = nameRegExp.test(name);
              const isLt1M = file.size / 1024 < 1024;
              if (!isImage) {
                message.error({
                  content: '文件类型错误, 请上传一个图片文件,支持格式jp(e)g或png',
                  key: 'upload_image',
                });
                rejects();
                return;
              }
              if (!isLt1M) {
                message.error({
                  content: '文件过大，请上传一个小于1M的文件',
                  key: 'upload_image',
                });
                rejects();
                return;
              }
              resolve(true);
            })
          }
        >
          <Upload
            action="/api/web-nav/v1.0.0/uploadBanner"
            listType="picture-card"
            accept="image/png, image/jpeg"
            name="banner_image"
            maxCount={1}
            onPreview={async (file: UploadFile) => {
              if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj as RcFile);
              }

              setPreviewImage(file.url || (file.preview as string));
              setPreviewVisible(true);
              setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
            }}
            onChange={(info) => {
              const { status, response, name } = info.file;

              if (status === 'uploading') {
                message.loading({
                  content: '图片处理中...',
                  key: 'upload_image',
                });
              }
              if (status === 'done' && response?.code === 0) {
                console.log('response.data', response.data);

                setBannerUrl(response.data);
                message.success({
                  content: response?.message || '上传成功',
                  key: 'upload_image',
                });
                return true;
              }
              if (status === 'error' || (response?.code && response?.code !== 0)) {
                const msg = response?.message || '';
                message.error({ content: `${name}上传失败。${msg}`, key: 'upload_image' });
                return false;
              }
              return false;
            }}
          >
            <Button icon={<UploadOutlined />} style={{ width: '105px', height: '105px' }}>
              <div>点击上传</div>
            </Button>
          </Upload>
        </ImgCrop>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={() => setPreviewVisible(false)}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
      <div style={{ padding: '0 70px' }}>
        <p>当前图片预览: </p>
        <img height={150} src={bannerUrl} />
      </div>
    </ModalForm>
  );
};

export default UpdateWebNavModal;
